import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/foundation.dart';
import 'device_config_service.dart';

class ImageService {
  static final ImagePicker _picker = ImagePicker();
  
  // 拍照获取图片
  static Future<File?> takePhoto() async {
    try {
      // 请求相机权限
      final status = await Permission.camera.request();
      if (!status.isGranted) {
        debugPrint('相机权限未授予');
        return null;
      }
      
      final XFile? photo = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 70, // 压缩图片质量以减少存储空间
      );
      
      if (photo != null) {
        // 将临时文件复制到应用目录
        final savedFile = await _saveImageToAppDir(File(photo.path), 'camera');
        return savedFile;
      }
      
      return null;
    } catch (e) {
      debugPrint('拍照时出错: $e');
      return null;
    }
  }
  
  // 从相册选择图片
  static Future<File?> pickImageFromGallery() async {
    try {
      // 请求相册权限
      final status = await Permission.photos.request();
      if (!status.isGranted) {
        debugPrint('相册权限未授予');
        return null;
      }
      
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 70,
      );
      
      if (image != null) {
        // 将临时文件复制到应用目录
        final savedFile = await _saveImageToAppDir(File(image.path), 'gallery');
        return savedFile;
      }
      
      return null;
    } catch (e) {
      debugPrint('选择图片时出错: $e');
      return null;
    }
  }
  
  // 将图片保存到应用目录
  static Future<File?> _saveImageToAppDir(File imageFile, String source) async {
    try {
      // 检查是否为专用设备模式
      final isDedicatedDevice = await DeviceConfigService.isDedicatedDevice();
      Directory imagesDir;
      
      if (isDedicatedDevice) {
        // 专用设备模式：使用专用路径
        final dedicatedPath = await DeviceConfigService.getDedicatedDevicePath();
        imagesDir = Directory('$dedicatedPath/answer_images');
        
        // 检查专用路径是否可访问
        try {
          if (!await imagesDir.exists()) {
            await imagesDir.create(recursive: true);
          }
          // 测试写入权限
          final testFile = File('${imagesDir.path}/.test_write');
          await testFile.writeAsString('test');
          await testFile.delete();
        } catch (e) {
          debugPrint('专用路径无法访问，回退到应用目录: $e');
          // 回退到应用目录
          final appDir = await getApplicationDocumentsDirectory();
          imagesDir = Directory('${appDir.path}/answer_images');
        }
      } else {
        // 普通模式：使用默认路径
        final appDir = await getApplicationDocumentsDirectory();
        imagesDir = Directory('${appDir.path}/answer_images');
      }
      
      // 确保目录存在
      if (!await imagesDir.exists()) {
        await imagesDir.create(recursive: true);
      }
      
      // 创建唯一文件名
      final fileName = '${DateTime.now().millisecondsSinceEpoch}_$source${path.extension(imageFile.path)}';
      final targetPath = '${imagesDir.path}/$fileName';
      
      // 复制文件到目标路径
      return await imageFile.copy(targetPath);
    } catch (e) {
      debugPrint('保存图片时出错: $e');
      // 最后的回退：尝试保存到应用临时目录
      try {
        final tempDir = await getTemporaryDirectory();
        final imagesDir = Directory('${tempDir.path}/answer_images');
        if (!await imagesDir.exists()) {
          await imagesDir.create(recursive: true);
        }
        final fileName = '${DateTime.now().millisecondsSinceEpoch}_$source${path.extension(imageFile.path)}';
        final targetPath = '${imagesDir.path}/$fileName';
        return await imageFile.copy(targetPath);
      } catch (e2) {
        debugPrint('回退保存也失败: $e2');
        return null;
      }
    }
  }
  
  // 根据考试ID和问题ID生成唯一的图片路径
  static Future<String> getImagePathForAnswer(String examId, String questionId) async {
    // 检查是否为专用设备模式
    final isDedicatedDevice = await DeviceConfigService.isDedicatedDevice();
    Directory imagesDir;
    
    if (isDedicatedDevice) {
      // 专用设备模式：使用专用路径
      final dedicatedPath = await DeviceConfigService.getDedicatedDevicePath();
      imagesDir = Directory('$dedicatedPath/answer_images');
      
      // 检查专用路径是否可访问
      try {
        if (!await imagesDir.exists()) {
          await imagesDir.create(recursive: true);
        }
        // 测试写入权限
        final testFile = File('${imagesDir.path}/.test_write');
        await testFile.writeAsString('test');
        await testFile.delete();
      } catch (e) {
        debugPrint('专用路径无法访问，使用应用目录: $e');
        // 回退到应用目录
        final appDir = await getApplicationDocumentsDirectory();
        imagesDir = Directory('${appDir.path}/answer_images');
      }
    } else {
      // 普通模式：使用默认路径
      final appDir = await getApplicationDocumentsDirectory();
      imagesDir = Directory('${appDir.path}/answer_images');
    }
    
    // 确保目录存在
    if (!await imagesDir.exists()) {
      await imagesDir.create(recursive: true);
    }
    
    // 使用考试ID和问题ID创建唯一文件名
    final fileName = '${examId}_${questionId}_${DateTime.now().millisecondsSinceEpoch}.jpg';
    return '${imagesDir.path}/$fileName';
  }
  
  // 删除图片
  static Future<bool> deleteImage(String imagePath) async {
    try {
      final file = File(imagePath);
      if (await file.exists()) {
        await file.delete();
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('删除图片时出错: $e');
      return false;
    }
  }
} 